< previous page page_497 next page >

Page 497
Creating Excel Objects
To start an instance of Excel, use the Workbook and Worksheet objects. The following code starts Excel and creates a new workbook containing one worksheet:
Dim objExcel As Excel.Application
Set objExcel = New Excel.Application
objExcel.Visible = True
objExcel.SheetsInNewWorkbook = 1
objExcel.Workbooks.Add
Setting Cell and Range Values
To set the values of individual cells in a worksheet, you can use the Cells collection or the Range property of the Worksheet object:
With objExcel.ActiveSheet
    .Cells(1,2).Value = "10"
    .Cells(2,2).Value = "20"
    .Cells(3,2).Value = "=SUM(B1:B2)"
    .Range("A3") = "Total"
End With
note.gifRange also works with named ranges of one or more cells:
objExcel.ActiveSheet.Range("myrange").Font.Color = vbRed square.gif

Notice that a With statement is used so that the object name is not repeated. In Excel, you may find that the object you need to reference is several levels deep in a collection:
ObjExcel.Workbooks(1).Sheets("Portfolio").Range(2,4).Font.Bold = True
Although this approach may seem confusing, it is a good way to organize a large number of classes. When you're programming Excel and Word, you can employ several methods to make working with collections easier:
Create an intermediate object variable.
Use the dot notation, as in the preceding line of code.
Use a With statement to avoid extra typing.
Using the OLE Container Control
The OLE Container control allows you to embed or link OLE objects in your program. In preceding sections, you learned about using OLE objects to control another application. Using the OLE control is different in that the external object appears on a form in your program rather than as a separate application. In other words, you can have a form with buttons, labels, and an OLE control that contains a Word document. You can create the embedded object either at designtime or runtime, as long as the OLE control has been placed on your form.

 
< previous page page_497 next page >